package com.ansys.demo.service.impl;

import com.ansys.demo.bean.Problem;
import com.ansys.demo.mapper.QuestionMapper;
import com.ansys.demo.service.FileService;
import com.ansys.demo.utils.DocUtil;
import com.ansys.demo.utils.MultipartFileToFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.List;
import java.util.regex.Pattern;


/**
 * @Author: panghai
 * @Date: 2022/04/04/20:15
 * @Description: 文件处理实现类
 */
@Service
public class UploadFileServiceImpl implements FileService {

    @Autowired
    private QuestionMapper questionMapper;

    /**
     * win系统的图片保存路径
     */
    @Value("${imagePathForWindow}")
    private String imagePathForWindow;

    /**
     * linux系统的图片保存路径
     */
    @Value("${imagePathForLinux}")
    private String imagePathForLinux;

    /**
     * 将上传的题库文件持久化
     *
     * @param multipartFile 题库文件
     */
    @Override
    public String uploadFile(MultipartFile multipartFile) throws Exception {

        // 文件上传路径
        String savePath;

        String os = System.getProperty("os.name").toLowerCase();
        if (os.startsWith("win")) {
            savePath = imagePathForWindow;
        }else{
            savePath = imagePathForLinux;
        }

        File file = MultipartFileToFile.multipartFileToFile(multipartFile);

        DocUtil.readWordImage(multipartFile.getOriginalFilename(), file, savePath);

        List<String> chineseList = DocUtil.chinese;
        List<String> zhuangList = DocUtil.zhuang;
        List<List<String>> optionsList = DocUtil.options;
        List<String> imgList = DocUtil.imgList;

        for (int i = 0; i < chineseList.size(); i++) {
            Problem p = new Problem();
            int sign = Integer.parseInt(Pattern.compile("[^0-9]").matcher(imgList.get(i)).replaceAll(""));
            p.setSign(i+1);
            p.setImgurl(imgList.get(i));
            p.setChinese(chineseList.get(sign-1));
            p.setZhuang(zhuangList.get(sign-1));
            List<String> strList = optionsList.get(sign-1);
            StringBuilder sb = new StringBuilder();
            for (int j = 0; j < strList.size(); j++) {
                sb.append(strList.get(j));
                if (j < strList.size() - 1) {
                    sb.append(";");
                }
            }
            p.setOption(sb.toString());
            if(questionMapper.checkQuestion(p)==0){
                questionMapper.insertQuestion(p);
            }
        }
        return "ok";
    }

}
